package com.example.myapplication.datastore

import android.content.Context
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.booleanPreferencesKey
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.floatPreferencesKey
import androidx.datastore.preferences.core.intPreferencesKey
import androidx.datastore.preferences.preferencesDataStore
import kotlinx.coroutines.flow.map

//1.往Context上下文对象中扩展一个DataStore实例
val Context.dataStore: DataStore<Preferences> by preferencesDataStore(name = "counter_app")

data class AppConfig(
    var fontSizeScale: Float = 1F,
    var darkMode: Boolean = false,
    var counter:Int = 0
)

//DataStore文件数据管理类，用于读取、写入首选项数据
class DataStoreManager(val context: Context) {
    //2. 指定一个键的名称
    companion object {
        //定义一个键的名称
        val COUNTER = intPreferencesKey("counter")
        val FONT_SIZE = floatPreferencesKey("fontSizeScale")
        val DARK_MODE = booleanPreferencesKey("darkMode")
    }

    //3.读取
    val appConfig = context.dataStore.data.map { preferences->
        AppConfig(
            counter = preferences[COUNTER]?:0,
            darkMode = preferences[DARK_MODE]?:false,
            fontSizeScale = preferences[FONT_SIZE]?:1F
        )
    }

    //4.改变计数器
    suspend fun setCounter(counter: Int){
        context.dataStore.edit { preferences->
            preferences[COUNTER] = counter
        }
    }

    //5.设置字体大小
    suspend fun setFontSizeScale(scale: Float){
        context.dataStore.edit { preferences->
            preferences[FONT_SIZE] = scale
        }
    }

    //5.设置深色模式
    suspend fun setDarkMode(darkMode: Boolean){
        context.dataStore.edit { preferences->
            preferences[DARK_MODE] = darkMode
        }
    }
}